package com.wyp.didishige.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.wyp.didishige.activity.ImageBrowserActivity;
import com.wyp.didishige.activity.NewRecordPlayClickListener;
import com.wyp.didishige.activity.users.UserInfoActivity;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.FaceTextUtils;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.utils.TimeUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.utils.ImageLoadOptions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMAudioMessage;
import cn.bmob.newim.bean.BmobIMImageMessage;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMMessageType;
import cn.bmob.newim.bean.BmobIMSendStatus;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobDownloadManager;
import cn.bmob.newim.listener.FileDownloadListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;


/**
 * 聊天适配器
 *
 */
@SuppressWarnings("ALL")
public class MessageChatAdapter extends BaseListAdapter<BmobIMMessage> {

    //文本
    private final int TYPE_RECEIVER_TXT = 0;
    private final int TYPE_SEND_TXT = 1;
    //图片
    private final int TYPE_SEND_IMAGE = 2;
    private final int TYPE_RECEIVER_IMAGE = 3;
    //位置
    private final int TYPE_SEND_LOCATION = 4;
    private final int TYPE_RECEIVER_LOCATION = 5;
    //语音
    private final int TYPE_SEND_VOICE =6;
    private final int TYPE_RECEIVER_VOICE = 7;
    //视频
    private final int TYPE_SEND_VIDEO =8;
    private final int TYPE_RECEIVER_VIDEO = 9;

    String currentObjectId = "";

    DisplayImageOptions options;

    private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

    public MessageChatAdapter(Context context, List<BmobIMMessage> msgList) {
        super(context, msgList);
        currentObjectId = BmobIM.getInstance().getCurrentUid();

        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .showImageOnFail(R.drawable.ic_launcher)
                .resetViewBeforeLoading(true)
                .cacheOnDisc(true)
                .cacheInMemory(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new FadeInBitmapDisplayer(300))
                .build();
    }

    public void addMessages(List<BmobIMMessage> messages) {
        bmobIMMessageList.addAll(0, messages);
        notifyDataSetChanged();
    }

    public void addMessage(BmobIMMessage message) {
        bmobIMMessageList.addAll(Arrays.asList(message));
        notifyDataSetChanged();
    }
    public int findPosition(BmobIMMessage message) {
        int index = this.getCount();
        int position = -1;
        while(index-- > 0) {
            if(message.equals(this.getItem(index))) {
                position = index;
                break;
            }
        }
        return position;
    }
    public int findPosition(long id) {
        int index = this.getCount();
        int position = -1;

        while(index-- > 0) {
            if(this.getItemId(index) == id) {
                position = index;
                break;
            }
        }

        return position;
    }

    public BmobIMMessage getFirstMessage() {
        if (null != bmobIMMessageList && bmobIMMessageList.size() > 0) {
            return bmobIMMessageList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public int getItemViewType(int position) {
        BmobIMMessage msg = bmobIMMessageList.get(position);
        if (msg.getMsgType().equals(BmobIMMessageType.IMAGE.getType())) {
            return msg.getFromId().equals(currentObjectId) ? TYPE_SEND_IMAGE : TYPE_RECEIVER_IMAGE;
        } else if (msg.getMsgType().equals(BmobIMMessageType.LOCATION.getType())) {
            return msg.getFromId().equals(currentObjectId) ? TYPE_SEND_LOCATION : TYPE_RECEIVER_LOCATION;
        } else if (msg.getMsgType().equals(BmobIMMessageType.VOICE.getType())) {
            return msg.getFromId().equals(currentObjectId) ? TYPE_SEND_VOICE : TYPE_RECEIVER_VOICE;
        } else {
            return msg.getFromId().equals(currentObjectId) ? TYPE_SEND_TXT : TYPE_RECEIVER_TXT;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 8;
    }

    private View createViewByType(BmobIMMessage message, int position) {
        if (message.getMsgType().equals(BmobIMMessageType.IMAGE.getType())) {//图片类型
            return getItemViewType(position) == TYPE_RECEIVER_IMAGE ?
                    mInflater.inflate(R.layout.item_chat_received_image, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_image, null);
        } else if (message.getMsgType().equals(BmobIMMessageType.LOCATION.getType())) {//位置类型
            return getItemViewType(position) == TYPE_RECEIVER_LOCATION ?
                    mInflater.inflate(R.layout.item_chat_received_location, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_location, null);
        } else if (message.getMsgType().equals(BmobIMMessageType.VOICE.getType())) {//语音类型
            return getItemViewType(position) == TYPE_RECEIVER_VOICE ?
                    mInflater.inflate(R.layout.item_chat_received_voice, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_voice, null);
        } else {//剩下默认的都是文本
            String extra = bmobIMMessageList.get(position).getExtra();
            if (extra != null && extra.equals("system")) {
                return mInflater.inflate(R.layout.item_chat_system_message, null);
            } else {
                return getItemViewType(position) == TYPE_RECEIVER_TXT ?
                        mInflater.inflate(R.layout.item_chat_received_message, null)
                        :
                        mInflater.inflate(R.layout.item_chat_sent_message, null);
            }
        }
    }

    @Override
    public View bindView(final int position, View convertView, ViewGroup parent) {
        final BmobIMMessage item = bmobIMMessageList.get(position);
        if (convertView == null) {
            convertView = createViewByType(item, position);
        }
        //系统消息
        TextView sys_message = ViewHolder.get(convertView, R.id.system_msg);

        //文本类型
        ImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar);
        final ImageView iv_fail_resend = ViewHolder.get(convertView, R.id.iv_fail_resend);//失败重发
        final TextView tv_send_status = ViewHolder.get(convertView, R.id.tv_send_status);//发送状态
        TextView tv_time = ViewHolder.get(convertView, R.id.tv_time);
        TextView tv_message = ViewHolder.get(convertView, R.id.tv_message);
        //图片
        ImageView iv_picture = ViewHolder.get(convertView, R.id.iv_picture);
        final ProgressBar progress_load = ViewHolder.get(convertView, R.id.progress_load);//进度条
        //位置
        TextView tv_location = ViewHolder.get(convertView, R.id.tv_location);
        //语音
        final ImageView iv_voice = ViewHolder.get(convertView, R.id.iv_voice);
        //语音长度
        final TextView tv_voice_length = ViewHolder.get(convertView, R.id.tv_voice_length);
        final BmobIMUserInfo info = item.getBmobIMUserInfo();
        //点击头像进入个人资料
        String avatar;
        if (item.getFromId().equals(currentObjectId)){
            avatar= BmobUser.getCurrentUser(mContext,User.class).getAvatar();
        }else{
            avatar = info!=null?info.getAvatar():"";
        }
        if (avatar != null && !avatar.equals("")) {
            ImageLoader.getInstance().displayImage(avatar, iv_avatar, ImageLoadOptions.avatarOptions);
        } else {
            ImageLoader.getInstance().displayImage("drawable://"+R.drawable.ic_launcher, iv_avatar, ImageLoadOptions.avatarOptions);
        }

        iv_avatar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle=new Bundle();
                bundle.putString(Config.KEY_USER_ID, item.getFromId());
                IntentUtil.start_activity((Activity) mContext, UserInfoActivity.class, bundle);
            }
        });

        tv_time.setText(TimeUtil.getChatTime(item.getCreateTime()));

        if (getItemViewType(position) == TYPE_SEND_TXT
//				||getItemViewType(position)==TYPE_SEND_IMAGE//图片单独处理
                || getItemViewType(position) == TYPE_SEND_LOCATION
                || getItemViewType(position) == TYPE_SEND_VOICE) {//只有自己发送的消息才有重发机制
            //状态描述
            if (item.getSendStatus() == BmobIMSendStatus.SENDED.getStatus()) {//发送成功
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                if (item.getMsgType().equals(BmobIMMessageType.VOICE.getType())) {
                    tv_send_status.setVisibility(View.GONE);
                    tv_voice_length.setVisibility(View.VISIBLE);
                } else {
                    tv_send_status.setVisibility(View.VISIBLE);
                    tv_send_status.setText("已发送");
                }
            } else if (item.getSendStatus() == BmobIMSendStatus.SENDFAILED.getStatus()) {//服务器无响应或者查询失败等原因造成的发送失败，均需要重发
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.VISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
                if (item.getMsgType() .equals(BmobIMMessageType.VOICE.getType())) {
                    tv_voice_length.setVisibility(View.GONE);
                }
            } else if (item.getSendStatus() == BmobIMSendStatus.RECEIPT.getStatus()) {//对方已接收到
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                if (item.getMsgType() .equals(BmobIMMessageType.VOICE.getType())) {
                    tv_send_status.setVisibility(View.GONE);
                    tv_voice_length.setVisibility(View.VISIBLE);
                } else {
                    tv_send_status.setVisibility(View.VISIBLE);
                    tv_send_status.setText("已阅读");
                }
            } else if (item.getSendStatus() == BmobIMSendStatus.SENDING.getStatus()) {//开始上传
                progress_load.setVisibility(View.VISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
                if (item.getMsgType().equals(BmobIMMessageType.VOICE.getType())) {
                    tv_voice_length.setVisibility(View.GONE);
                }
            }
        }
        //根据类型显示内容
        final String text = item.getContent();
        if (item.getMsgType() .equals(BmobIMMessageType.IMAGE.getType())) {//图片类型
            try {
                if (text != null && !text.equals("")) {//发送成功之后存储的图片类型的content和接收到的是不一样的
                    dealWithImage(position, progress_load, iv_fail_resend, tv_send_status, iv_picture, item);
                }
                iv_picture.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(mContext, ImageBrowserActivity.class);
                        ArrayList<BmobFile> files=new ArrayList<BmobFile>();
                        BmobFile bmobFile = new BmobFile();
                        bmobFile.setUrl(getImageUrl(item));
                        files.add(bmobFile);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("photos",files);
                        bundle.putInt("position",0);
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }
                });

            } catch (Exception e) {
            }
        } else if (item.getMsgType() .equals(BmobIMMessageType.LOCATION.getType())) {//位置类型
            return getItemViewType(position) == TYPE_RECEIVER_LOCATION ?
                    mInflater.inflate(R.layout.item_chat_received_location, null)
                    :
                    mInflater.inflate(R.layout.item_chat_sent_location, null);
        } else if (item.getMsgType() .equals(BmobIMMessageType.VOICE.getType())) {//语音类型
            try {
                //显示特有属性
                final BmobIMAudioMessage message = BmobIMAudioMessage.buildFromDB(false, item);
                if (text != null && !text.equals("")) {
                    tv_voice_length.setVisibility(View.VISIBLE);
                    String content = item.getContent();
                    if (item.getFromId().equals(currentObjectId)) {//发送的消息
                        if (item.getSendStatus() == BmobIMSendStatus.RECEIPT.getStatus()
                                || item.getSendStatus() == BmobIMSendStatus.SENDED.getStatus()) {//当发送成功或者发送已阅读的时候，则显示语音长度
                            tv_voice_length.setVisibility(View.VISIBLE);
                            String length = content.split("&")[2];
                            tv_voice_length.setText(String.format("%s''", length));
                        } else {
                            tv_voice_length.setVisibility(View.INVISIBLE);
                        }
                    } else {//收到的消息
                        boolean isExists = BmobDownloadManager.isAudioExist(currentObjectId, item);

                        if (!isExists) {//若指定格式的录音文件不存在，则需要下载，因为其文件比较小，故放在此下载
                            String netUrl = content.split("&")[0];
                            final String length = content.split("&")[1];
                            BmobDownloadManager downloadTask = new BmobDownloadManager(mContext, item, new FileDownloadListener() {

                                @Override
                                public void onStart() {
                                    progress_load.setVisibility(View.VISIBLE);
                                    tv_voice_length.setVisibility(View.GONE);
                                    iv_voice.setVisibility(View.INVISIBLE);//只有下载完成才显示播放的按钮
                                }
                                @Override
                                public void done(BmobException e) {
                                    if(e==null){
                                        progress_load.setVisibility(View.GONE);
                                        tv_voice_length.setVisibility(View.VISIBLE);
                                        tv_voice_length.setText(String.format("%s''", message.getDuration()));
                                        iv_voice.setVisibility(View.VISIBLE);
                                    }else{
                                        progress_load.setVisibility(View.GONE);
                                        tv_voice_length.setVisibility(View.GONE);
                                        iv_voice.setVisibility(View.INVISIBLE);
                                    }
                                }

                            });
                            downloadTask.execute(netUrl);
                        } else {
                            String length = content.split("&")[2];
                            tv_voice_length.setText(length + "\''");
                        }
                    }
                }
                //播放语音文件
                iv_voice.setOnClickListener(new NewRecordPlayClickListener(mContext, message, iv_voice));
            } catch (Exception e) {

            }
        } else {//剩下默认的都是文本
            try {
                String extra = bmobIMMessageList.get(position).getExtra();
                if (extra != null && extra.equals("system")) {
                    sys_message.setText(text);
                } else {
                    SpannableString spannableString = FaceTextUtils
                            .toSpannableString(mContext, text);
                    tv_message.setText(spannableString);
                }

            } catch (Exception e) {
            }
        }

        return convertView;
    }

    /**
     * 获取图片的地址--
     *
     * @param  item
     */
    private String getImageUrl(BmobIMMessage item) {
        String showUrl = "";
        BmobIMImageMessage imImageMessage=BmobIMImageMessage.buildFromDB(true,item);
        showUrl = StringUtils.isNullOrEmpty(imImageMessage.getRemoteUrl())?imImageMessage.getLocalPath():imImageMessage.getRemoteUrl();
        return showUrl;
    }


    /**
     * 处理图片
     *
     */
    private void dealWithImage(int position, final ProgressBar progress_load, ImageView iv_fail_resend, TextView tv_send_status, ImageView iv_picture, BmobIMMessage item) {
        //如果是发送的图片的话，因为开始发送存储的地址是本地地址，发送成功之后存储的是本地地址+"&"+网络地址，因此需要判断下
        BmobIMImageMessage imImageMessage=BmobIMImageMessage.buildFromDB(true,item);
        String showUrl = StringUtils.isNullOrEmpty(imImageMessage.getRemoteUrl())?imImageMessage.getLocalPath():imImageMessage.getRemoteUrl();
        //为了方便每次都是取本地图片显示
        if (getItemViewType(position) == TYPE_SEND_IMAGE) {//发送的消息
            if (item.getSendStatus() == BmobIMSendStatus.SENDING.getStatus()) {
                progress_load.setVisibility(View.VISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
            } else if (item.getSendStatus() == BmobIMSendStatus.SENDED.getStatus()) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.VISIBLE);
                tv_send_status.setText("已发送");
            } else if (item.getSendStatus() == BmobIMSendStatus.SENDFAILED.getStatus()) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.VISIBLE);
                tv_send_status.setVisibility(View.INVISIBLE);
            } else if (item.getSendStatus() == BmobIMSendStatus.RECEIPT.getStatus()) {
                progress_load.setVisibility(View.INVISIBLE);
                iv_fail_resend.setVisibility(View.INVISIBLE);
                tv_send_status.setVisibility(View.VISIBLE);
                tv_send_status.setText("已阅读");
            }

            ImageLoader.getInstance().displayImage(showUrl, iv_picture);
        } else {
            ImageLoader.getInstance().displayImage(showUrl, iv_picture, options, new ImageLoadingListener() {

                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progress_load.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view,
                                            FailReason failReason) {
                    progress_load.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    progress_load.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                    progress_load.setVisibility(View.INVISIBLE);
                }
            });
        }
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

}
